import React, {useState} from 'react'
import {View, Text } from '@tarojs/components'
import {AtInput, AtButton} from 'taro-ui'
import Taro, {useRouter} from "@tarojs/taro"
import {getEnv} from "../../env";
import userStore from "../../store/userStore"
import './index.scss'

export default () => {
  const {params: {openId}} = useRouter<{ openId: string }>()
  const [phone, setPhone] = useState<string>("");
  const [vcode, setVcode] = useState<string>("");
  const [waitNum, setWaitNum] = useState<number>(0);

  async function sendVcode() {
    if (!(/^1[3456789]\d{9}$/.test(phone))) return Taro.showToast({
      title: "请输入正确的手机号码",
      icon: "none"
    })

    await Taro.request({
      url: `${getEnv().baseUrl}/user/sendMsg/${phone}`,
      method: "POST"
    })

    Taro.showToast({
      title: "发送成功，请注意查收",
    })


    let num = 60;
    setWaitNum(() => {
      const inter = setInterval(() => {
        if (num <= 0) return clearInterval(inter);
        setWaitNum(--num);
      }, 1000)
      return num
    })
  }

  // 提交绑定
  async function onSubmit() {
    if (!(/^1[3456789]\d{9}$/.test(phone))) return Taro.showToast({
      title: "请输入正确的手机号码",
      icon: "none"
    })
    if (!vcode) return Taro.showToast({
      title: "请输入验证码",
      icon: "none"
    })
    Taro.showLoading({mask:true,title:"加载中"});
    await Taro.request({
      url: `${getEnv().baseUrl}/user/bindPhone`,
      method: "POST",
      data: {
        openId: openId,
        phone: phone,
        vcode: vcode
      }
    }).finally(()=> Taro.hideLoading())
    userStore.getState(state => {
      userStore.dispatch("set", {...state.value, isLogin: true, mobile: phone})
      Taro.showToast({title:"登录成功",icon:"success"})
      Taro.reLaunch({
        url: "/pages/index/index"
      })
    })

  }

  return <View className='wing-blank wing-space'>
    <AtInput
      required
      name='value'
      type='phone'
      title='手机号'
      placeholder='请输入手机号'
      value={phone}
      onChange={(value) => setPhone(value as string)}
    />
    <AtInput
      required
      name='value1'
      type='number'
      title='验证码'
      placeholder='请输入验证码'
      value={vcode}
      onChange={(value) => setVcode(value as string)}
    >
      {
        !waitNum ? <Text onClick={sendVcode}>发送验证码</Text> :
          <Text style={{color: "grey"}}>{waitNum} 秒</Text>
      }
    </AtInput>
    <View style={{marginTop: "50px"}}>
      <AtButton onClick={onSubmit}>登录</AtButton>
    </View>
  </View>
}

